var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const fs = require('fs')

var libDate = require('./lib/lib_date');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var checkPoint = require('./routes/checkpoint')

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');


//日志相关
logger.token('nowTime', function(req, res){
  return "[" + libDate.formatTime('Y-m-d H:i:s') + "]";
});
logger.token('httpParams', function(req, res){
  return "   query: " + JSON.stringify(req.query) + "     body: " + JSON.stringify(req.body);
});
logger.format('access', '[access] :nowTime :method :status :url :httpParams');
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'runtime','access.log'), {flags: 'a'});
app.use(logger('dev'));
app.use(logger('access',{stream: accessLogStream}));


app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(function(req, res, next){
    res.header('Access-Control-Allow-Origin', "*");
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Credentials','true');
  console.log('next');
  next();
});


app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/checkpoint', checkPoint);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
